package psn.zjk.common.consistentHash;

import com.google.common.hash.Hashing;
import org.apache.commons.lang3.RandomStringUtils;

/**
 * @author zhangjk
 * @CREATE_TIME 2020/12/2 9:37
 */
public class JumpConsistentHash {

    public static long hash(Object object, int num_buckets) {
        long key = object.hashCode();
        long b = -1, j = 0;
        while (j < num_buckets) {
            b = j;
            key = key * 2862933555777941757L + 1;
            j = (long) ((b + 1) * ((1L << 31) / toDouble((key >> 33) + 1)));
        }
        return b;
    }

    private static  double toDouble(final long n){
        double d=n & 0x7fffffffffffffffL;//63个1，意为取绝对值
        if(n<0){
            d+=0x1.0p63;//第64位，首位表示正负
        }
        return  d;
    }

    public static void main(String[] args) {
        int i = RandomStringUtils.random(4).hashCode();
        double pow = Math.pow(2, 32);
        System.out.println(Hashing.consistentHash(i, (int) pow));
        System.out.println(JumpConsistentHash.hash(i, (int) pow));
    }
}